
class Promise{
	catch(onRejected){
		return this.then(undefined,onRejected);
	}
	static #FULFILLED = "fulfilled";
	static #PENDING = "pending";
	static #REJECTED = "rejected";
	callback=[];
	// 将状态更新为成功-fulfilled,value为成功值
	static #resolved(value){
		if(this.state !== Promise.#PENDING) return;
		this.state = Promise.#FULFILLED;
		this.result = value;
		this.callback.forEach(item=>{
			item.onResolved();
		})
	}
	// 将状态更新为失败-rejected,value为失败值
	static #rejected(value){
		if(this.state !== Promise.#PENDING) return;
		this.state = Promise.#REJECTED;
		this.result = value;
		this.callback.forEach(item=>{
			item.onRejected();
		})
	}
	constructor(executor) {
		this.state = Promise.#PENDING;
		this.result = undefined;
		try{
			executor(Promise.#resolved.bind(this),Promise.#rejected.bind(this));
		}catch (err){
			Promise.#rejected.call(this,err)
		}
	}
	// onResolved:成功回调，onRejected是失败回调
	then(onResolved,onRejected){
		if(!(onResolved instanceof Function)) {
			onResolved = value=>value;
		}
		if(!(onRejected instanceof Function)){
			onRejected = reason=>{
				throw reason;
			}
		}
		return new Promise((resolve,reject)=>{
			const common = (callback)=>{
				setTimeout(()=>{
					try{
						const result = callback(this.result);
						// 判断成功回调返回的是否为Promise实例
						if(result instanceof Promise){
							result.then(resolve,reject)
						}else{
							resolve(result);
						}
					}catch (err){
						reject(err);
					}
				})
			}
			if(this.state === Promise.#FULFILLED){
				common(onResolved);
			}
			else if(this.state === Promise.#REJECTED){
				common(onRejected)
			}else if(this.state === Promise.#PENDING){
				// console.log(this.state);
				this.callback.push({
					onResolved:common.bind(null,onResolved),
					onRejected:common.bind(null,onRejected)
				})
			}
		})
	}
	
}
export default Promise;